import axios from "axios"

export interface SQLControler {
    method: string,
    table: string,
    keys: Array<string>,
    key_types: Array<string>,
    values: Array<string> | null,
    where: Array<string> | null,
    where_key: string | null,
    group_by_keys: string | Array<string> | null,
    order_by_keys: string | Array<string> | null,
    limit: number | null,
}

async function ctrlSQL(ctrlKey: SQLControler): Promise<any> {
    let ans
    let method_dict = { select: 'get', update: 'put', delete: 'delete', insert: 'post' }
    if (ctrlKey.group_by_keys instanceof Array) ctrlKey.group_by_keys = ctrlKey.group_by_keys.join(' ')
    if (ctrlKey.order_by_keys instanceof Array) ctrlKey.order_by_keys = ctrlKey.order_by_keys.join(' ')
    await axios({
        method: method_dict[ctrlKey.method as keyof typeof method_dict],
        url: '/api/sql-deal',
        data: ctrlKey,
    }).then((res) => {
        ans = res
    }).catch((err) => {
        console.error(err)
    })
    return ans
}

export default { 
    ctrlSQL
}